package com.group1.bookmanagement.action;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.HttpParameters;
import org.apache.struts2.dispatcher.Parameter;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.group1.bookmanagement.domain.Label;
import com.group1.bookmanagement.domain.Photo;
import com.group1.bookmanagement.domain.User;
import com.group1.bookmanagement.service.LabelService;
import com.group1.bookmanagement.service.UserService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

@Controller("userAction")
@Scope("prototype")
public class UserAction extends ActionSupport implements ModelDriven<User> {

	private static final long serialVersionUID = 1L;

	@Resource(name = "userService")
	private UserService userService;
	@Resource(name = "labelService")
	private LabelService labelService;
	private User user = new User();
	// json数据集合
	private Map<String, Object> json;
	
	/**
	 * 跳转到登录页面
	 * @return
	 */
	public String toLogin() {
		HttpServletRequest request = ServletActionContext.getRequest();
		Cookie[] cookies = request.getCookies();
		
		for(Cookie cookie : cookies) {
			if (cookie.getName().equals("username")) {
				String username = cookie.getValue();
				request.setAttribute("username", username);
			}
		}
		
		return SUCCESS;
	}

	/**
	 * 登录
	 * @return
	 */
	public String login() {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		
		String remember = request.getParameter("remember");
		if (remember != null) {
			String username = request.getParameter("username");
			response.addCookie(new Cookie("username", username));
		} else {
			response.addCookie(new Cookie("username", null));
		}
		
		HttpSession session = request.getSession();
		//服务端的验证码
		String code_session = (String) session.getAttribute("code");
		//用户输入的验证码
		String code_input = request.getParameter("code").toUpperCase();
		if (code_session == null || code_input == null || !code_session.equals(code_input)) {
			return LOGIN;
		}
		
		User user_login = userService.login(user);
		if (user_login != null) {
			//将凭据保存在客户端
			Cookie cookie = new Cookie("loginCredential", user_login.getAutoLoginCredential());
			response.addCookie(cookie);
			//将登陆的用户信息保存在服务器
			session.setAttribute("user", user_login);
			return SUCCESS;
		}

		return LOGIN;
	}
	
	public String logout() {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();
		session.removeAttribute("user");
		return SUCCESS;
	}
	
	/**
	 * 自动登录
	 * @return
	 */
	public String autoLogin() {
		HttpServletRequest request = ServletActionContext.getRequest();
		Cookie[] cookies = request.getCookies();
		String loginCredential = null;
		User user = null;
		
		for(Cookie cookie : cookies) {
			if (cookie.getName().equals("loginCredential")) {
				loginCredential = cookie.getValue();
			}
		}
		
		if (loginCredential != null) {
			user = userService.autoLogin(loginCredential);
		}
		
		if (user != null) {
			return SUCCESS;
		}
		
		return LOGIN;
	}

	/**
	 * 注册
	 * @return
	 */
	public String register() {
		ActionContext context = ActionContext.getContext();
		userService.saveUser(user);

		return SUCCESS;
	}

	/**
	 * 删除
	 * @return
	 */
	public String delete() {
		ActionContext context = ActionContext.getContext();
		HttpParameters params = context.getParameters();
		Parameter param = params.get("id");
		Integer id = Integer.valueOf(param.getValue());
		User user = userService.getUser(id);
		userService.deleteUser(user);

		return SUCCESS;
	}
	
	private File file;

	/**
	 * 编辑
	 * @return
	 */
	public String edit() {
		HttpServletRequest request = ServletActionContext.getRequest();
		if (file != null) {
			Photo photo = new Photo(file);
			photo.upload(request);
			user.setAvator(photo);
		}
		userService.updateUser(user);
		request.getSession().setAttribute("user", userService.getUser(user.getId()));
		
		return SUCCESS;
	}
	
	/**
	 * 忘记密码
	 * @return
	 */
	public String forgotPassword() {
		ActionContext context = ActionContext.getContext();
		HttpParameters params = context.getParameters();
		Parameter param_username = params.get("username");
		String username = param_username.getValue();
		User user = userService.findUserByUsername(username);
		String email = user.getEmail();
		if (email == null) {
			return "bindEmail";
		}
		
		HttpServletRequest request = ServletActionContext.getRequest();
		userService.forgotPassword(request, user);
		
		return SUCCESS;
	}
	
	/**
	 * 修改密码
	 * @return
	 */
	public String changePassword() {
		ActionContext context = ActionContext.getContext();
		HttpParameters params = context.getParameters();
		Parameter param_id = params.get("id");
		Integer id = Integer.valueOf(param_id.getValue());
		//获取到用户
		User user = userService.getUser(id);
		Parameter param_password = params.get("password");
		//获取到新密码
		String password = param_password.getValue();
		user.setPassword(password);
		userService.changPassword(user);
		return SUCCESS;
	}

	/**
	 * 查询
	 * @return
	 */
	public String get() {
		ActionContext context = ActionContext.getContext();
		HttpParameters params = context.getParameters();
		Parameter param = params.get("id");
		Integer id = Integer.valueOf(param.getValue());
		User user = userService.getUser(id);
		context.put("user", user);

		return SUCCESS;
	}

	/**
	 * 查询所有
	 * @return
	 */
	public String list() {
		ActionContext context = ActionContext.getContext();
		List<User> list = userService.listUser(0);
		context.put("list", list);

		return SUCCESS;
	}

	/**
	 * 用户名是否存在
	 * @return
	 */
	public String isUsernameExist() {
		boolean isExist = userService.isUsernameExist(user.getUsername());
		json = new HashMap<>();
		json.put("isExist", isExist);

		return SUCCESS;
	}
	
	/**
	 * 绑定label
	 * @return
	 */
	public String addLabel() {
		ActionContext context = ActionContext.getContext();
		HttpParameters params = context.getParameters();
		//获取要绑定的label
		Parameter param_labelId = params.get("labelId");
		Long labelId = Long.valueOf(param_labelId.getValue());
		Label label = labelService.get(labelId);
		//获取用户
		HttpSession session = ServletActionContext.getRequest().getSession();
		User user = (User) session.getAttribute("user");
		//绑定
		userService.addLabel(user, label);
		
		return SUCCESS;
	}
	
	/**
	 * 解除绑定
	 * @return
	 */
	public String removeLabel() {
		ActionContext context = ActionContext.getContext();
		HttpParameters params = context.getParameters();
		//获取要解除绑定的label
		Parameter param_labelId = params.get("labelId");
		Long labelId = Long.valueOf(param_labelId.getValue());
		Label label = labelService.get(labelId);
		//获取用户
		HttpSession session = ServletActionContext.getRequest().getSession();
		User user = (User) session.getAttribute("user");
		//解除绑定
		userService.removeLabel(user, label);
		
		return SUCCESS;
	}

	@Override
	public User getModel() {
		return user;
	}

	public Map<String, Object> getJson() {
		return json;
	}

	public void setJson(Map<String, Object> json) {
		this.json = json;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

}
